package cz.cvut.fel.loader;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cz.cvut.fel.persister.FileSystemPersister;
import cz.cvut.fel.persister.MongoDBPersister;
import cz.cvut.fel.persister.RiakPersister;
import cz.cvut.fel.stats.Statistics;

public class Main {
/*
 * 0. data input (/ disk path or rabbitmq path)
 * 1. parametr DB servery
 * 2. parametr pocet vlaken
 */
	final static Logger log = LoggerFactory.getLogger(Main.class);

	public static AtomicInteger remaining = new AtomicInteger();
	
	public static void main(String[] args) throws Exception {
		Random r = new Random();
		// Get input params
		String path = args[0];
		
		String[] servers = args[1].split(","); 
		Integer threadCount = Integer.parseInt(args[2]);
		LoadJob[] jobs = new LoadJob[threadCount];
		
		Persister fs = new FileSystemPersister(path);
		fs.start();
		
		
		
		for (int i = 0; i < jobs.length; i++) {
			//Persister riak = new RiakPersister(servers[r.nextInt(servers.length)],null);
			//riak.connect();
			Persister persister = new MongoDBPersister(servers[r.nextInt(servers.length)],null);
			jobs[i] = new LoadJob(fs, persister);			
		}
		
		log.info("Loaded thread: "+jobs.length);
		
		for (int i = 0; i < jobs.length; i++) {
			jobs[i].start();
			remaining.getAndIncrement();
		}
		
		long testStartTime = System.currentTimeMillis();
		long epoch = 0;
		int total = 0;
		long latency = 0;
		int oldTotal;
		long oldLatency;
		
		while(remaining.get() != 0) {
	       Thread.sleep(1000);
	        
	        epoch++;
	        
	        epoch = 0;

            oldTotal    = total;
            oldLatency  = latency;

            Statistics stats = Statistics.getInstance(); 
            total    = stats.docs.get();
            latency  = stats.latency.get();

            int opDelta  = total - oldTotal;
            double latencyDelta = latency - oldLatency;

            long currentTimeInSeconds = (System.currentTimeMillis() - testStartTime) / 1000;
            String formattedDelta = (opDelta > 0) ? Double.toString(latencyDelta / (opDelta * 1000)) : "NaN";

            System.out.println(String.format("%d,%d,%s,%d", total, opDelta, formattedDelta, currentTimeInSeconds));// + ", -> Debug: min:"+al[0].get()+" max: "+al[1]);
		}
		
		
		for (int i = 0; i < jobs.length; i++) {
			jobs[i].join();
			jobs[i].getOut().disconnect();
		}
		log.info("Stop");
		
	}

}
